package k8s_agent

import (
	"context"
	"encoding/json"
	"fmt"

	dynamic_client "k8s.io/client-go/dynamic"

	devcontainer_api_v1 "code.gitea.io/gitea/modules/devstar_devcontainer/k8s_agent/api/v1"
	devcontainer_dto "code.gitea.io/gitea/modules/devstar_devcontainer/k8s_agent/dto"
	devcontainer_errors "code.gitea.io/gitea/modules/devstar_devcontainer/k8s_agent/errors"
)

// ListDevcontainers 根据条件列举 DevContainer
func ListDevcontainers(ctx *context.Context, client dynamic_client.Interface, opts *devcontainer_dto.ListDevcontainersOptions) (*devcontainer_api_v1.DevcontainerAppList, error) {

	if ctx == nil || opts == nil || len(opts.Namespace) == 0 {
		return nil, devcontainer_errors.ErrIllegalDevcontainerParameters{
			FieldList: []string{"ctx", "namespace"},
			Message:   "cannot be empty",
		}
	}

	list, err := client.Resource(groupVersionResource).Namespace(opts.Namespace).List(*ctx, opts.ListOptions)
	if err != nil {
		return nil, devcontainer_errors.ErrOperateDevcontainer{
			Action:  fmt.Sprintf("List Devcontainer in namespace '%s'", opts.Namespace),
			Message: err.Error(),
		}
	}
	// JSON 反序列化为 DevcontainerAppList
	jsonData, err := list.MarshalJSON()
	if err != nil {
		return nil, devcontainer_errors.ErrOperateDevcontainer{
			Action:  "verify JSON data of Devcontainer List",
			Message: err.Error(),
		}
	}
	devcontainerList := &devcontainer_api_v1.DevcontainerAppList{}
	if err := json.Unmarshal(jsonData, devcontainerList); err != nil {
		return nil, devcontainer_errors.ErrOperateDevcontainer{
			Action:  "deserialize Devcontainer List data",
			Message: err.Error(),
		}
	}
	return devcontainerList, nil
}
